<?php
namespace app\admin\service;

use app\common\model\StudentModel as StudentModel;
use app\admin\validate\StudentValidate as StudentValidate;
use app\common\exception\ServiceException;

class StudentService
{

    public static function getList($param)
    {
        $pagination = filter_pagination(@$param['page'], @$param['limit']);
        $data = [];
        $where = $where=[];
        if(!empty($param['study_date'])){
            $where[] = ['study_date','like','%'.$param['study_date'].'%'];
        }
        if(isset($param['status'])&&is_numeric($param['status'])){
            $where[] = ['status','=',$param['status']];
        }

        $where[] = ['status', '<>', -1];
        $query = StudentModel::field("id,weight,create_time,study_date,study_hours,content,status")->where($where)->order(["weight" => "desc", "create_time" => "desc"]);
        $data['total'] = $query->count();
        $data['dataList'] = [];
        if ($data['total']) {
            $data['dataList'] = $query->limit($pagination['start'], $pagination['limit'])->append(['status_text'])->select()->toArray();
        }
        return $data;
    }

    public static function save($param)
    {
        $validate = new StudentValidate();
        if (isset($param['id']) && $param['id']) {
            $validate = $validate->scene(StudentValidate::SCENE_EDIT);
            $model = StudentModel::get($param['id']);
        } else {
            $validate = $validate->scene(StudentValidate::SCENE_ADD);
            $model = new StudentModel();
        }
        if (!$validate->check($param)) {
            throw  new ServiceException($validate->getError());
        }
        $res = $model->save($param);
        if ($res) {
            return $model->id;
        } else {
            return false;
        }
    }


     public static function del($param)
     {
        return StudentModel::where([["id", "in", $param['id']]])->update(["status" => -1]);
     }


}